package com.jack.concurrent.limit;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by JackGe on 2017/7/10.
 */
public class Passer {

    private FlowConfig config = null;
    private AtomicInteger executeQueue = new AtomicInteger(0);
    private AtomicInteger waiteQueue = new AtomicInteger(0);

    public Passer setConfig(FlowConfig config) {
        this.config = config;
        return this;
    }

    public boolean canPass() {
        if (tryExecute()) {
            return true;
        } else {
            if (tryWait()) {
                long begin = System.currentTimeMillis();
                while (true) {
                    try {
                        Thread.sleep(30L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (tryExecute()) {
                        return true;
                    } else {
                        if (System.currentTimeMillis() - begin > this.config.getWaitTime()) {
                            this.waiteQueue.decrementAndGet();
                            return false;
                        } else {
                            continue;
                        }
                    }
                }
            } else {
                return false;
            }
        }
    }

    public void releaseExecute() {
        this.executeQueue.decrementAndGet();
    }

    private boolean tryWait() {
        int count = this.waiteQueue.incrementAndGet();
        if (count < this.config.getWaitCount()) {
            return true;
        } else {
            this.waiteQueue.decrementAndGet();
            return false;
        }
    }

    private boolean tryExecute() {
        int count = this.executeQueue.incrementAndGet();
        if (count < this.config.getWaitCount()) {
            return true;
        } else {
            this.executeQueue.decrementAndGet();
            return false;
        }
    }


}
